<template>
  <div>
    <!-- 权限管理 -->
    <div class="gva-table-box">
      <div>
        <label for="userName">角色名称：</label>
        <el-input placeholder="角色名称" v-model="roleName"
                  @change="searchJuris"></el-input>
        <el-button type="primary" style="margin-left: 10px" icon="search" @click="searchJuris">查询</el-button>
        <el-button icon="refresh" @click="clear">重置</el-button>
      </div>

      <div class="gva-btn-list" style="margin-top: 2%">
        <el-button icon="plus" type="primary"
                   @click="dialogState = true, isAdd = true">添加角色
        </el-button>
      </div>
      <!-- main表格区域 -->
      <el-table :data="tableData" v-loading="loading" :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }" row-key="roleId">
        <el-table-column prop="roleId" label="角色 ID"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="updateTime" label="修改时间"></el-table-column>
        <el-table-column prop="index" label="菜单权限分配" min-width="90">
          <template #default="scope">
            <el-cascader :options="menuList" :show-all-levels="false" width="250" collapse-tags-tooltip
                         :props="{ value: 'menuId', label: 'title', children: 'children', multiple: true }"
                         v-model="scope.row.rights" collapse-tags @change="changeSelect(scope.row)"
                         @visible-change="visibleChange"></el-cascader>
          </template>
        </el-table-column>

        <el-table-column align="left" label="查看全部数据" min-width="55">
          <template #default="scope">
            <el-switch v-model="scope.row.isAll" inline-prompt :active-value="true" :inactive-value="false"
                       @change="() => { switchEnable(scope.row) }"/>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button type="primary" icon="edit" @click="dialogState = true, isAdd = false"
                       v-on:click="updateBtn(scope.row)" link plain>编辑
            </el-button>
            <el-button type="danger" icon="delete" @click="delRoleBtn(scope.row)" link plain>删除
            </el-button>
            <el-button type="warning" icon="delete" plain
                       @click="delRole(scope.row.roleId)" link>清空权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination :current-page="page" :page-size="limit"
                       :page-sizes="[10, 30, 50, 100]" :total="total"
                       layout="total, sizes, prev, pager, next, jumper"
                       :hide-on-single-page="limit===10"
                       @current-change="handleCurrentChange" @size-change="handleSizeChange"/>
      </div>

    </div>
    <!-- 新增\修改角色模态框 -->
    <el-dialog :title="isAdd ? '新增角色' : '修改角色'" v-model="dialogState" width="30%">
      <el-form :inline="true">
        <el-form-item label="角色名称">
          <el-input placeholder="请输入角色名称" v-model="addForm.roleName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogState = false">取 消</el-button>
          <el-button type="primary" @click="isAdd?addRoleBtn():updateTrue()">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {delRights, getRights, editRights} from '@/api/menuAuth'
import {getMenuList, setRoleDataAuth} from '@/api/menu'
import {createAuthority, deleteAuthority, updateAuthority} from '@/api/authority'
import {ElMessage} from "element-plus";
import {nextTick} from "vue";
import {setUserInfo} from "@/api/user";

export default {
  data() {
    return {
      tableData: [],
      updateRights: false,
      addDialog: {
        permissionName: '',
        menuId: '',
      },
      menus: [],
      menuList: [],
      menuId: [],
      obj: {
        roleId: '',
        menuIds: []
      },
      addForm: {
        roleId: '',
        roleName: '',
        isAll: ''
      },
      updateActive: true,
      changeActive: false,
      roleName: '',
      loading: true,
      page: 1,
      limit: 10,
      total: 0,
      isAdd: false,
      dialogState: false
    }
  },
  mounted() {
    this.searchJuris()
  },
  methods: {
    //分页组件
    handleSizeChange(val) {
      this.limit = val
      this.searchJuris()
    },
    handleCurrentChange(val) {
      this.page = val
      this.searchJuris()
    },
    //重置按钮
    clear() {
      this.roleName = ''
      this.searchJuris()
    },
    //获取菜单列表
    async MenuList() {
      const res = await getMenuList({page: 1, pageSize: 999})
      const menus = res.data.records
      this.menus = menus
      // 过滤出pid为'0'的菜单项，作为主菜单列表
      const menuList = menus.filter(item => item.parentId === '0')
      // 过滤出pid不为'0'的菜单项，作为子菜单列表
      const childs = menus.filter(item => item.parentId !== '0')
      // 遍历主菜单列表
      menuList.forEach(li => {
        // 过滤出当前主菜单的子菜单项
        const children = childs.filter(child => child.parentId === li.menuId)
        // 如果存在子菜单项，则将其赋值给当前主菜单的children属性
        if (children.length !== 0) {
          li.children = children
        }
      })
      // 将结果赋值给类成员变量
      this.menuList = menuList
    },
    // 修改值触发
    changeSelect(row) {
      this.changeActive = true
      this.obj.roleId = row.roleId
      let mIds = []
      row.rights.forEach(r => {
        mIds.push(+r[1])
      })
      this.obj.menuIds = mIds
      if (this.updateActive) {
        this.update()
      }
    },
    async switchEnable(row) {
      this.addForm = JSON.parse(JSON.stringify(row))
      await nextTick()
      const req = {
        ...this.addForm
      }
      const res = await setRoleDataAuth(req)
      if (res.code === 0) {
        ElMessage({type: 'success', message: res.msg})
      }
      await this.searchJuris()
    },
    async update() {
      if (this.updateActive) {
        const res = await editRights(this.obj)
        if (res.code === 0) {
          ElMessage({type: 'success', message: res.msg})
          await this.searchJuris()
        }
      }
    },
    //下拉改变事件
    visibleChange(val) {
      this.updateActive = !val
      if (this.updateActive && this.changeActive) {
        this.changeActive = !this.changeActive
        this.update()
        this.changeActive = false
      }
    },
    // 模糊查询事件
    async searchJuris() {
      this.loading = true
      await this.MenuList()
      const res = await getRights({page: this.page, pageSize: this.limit, roleName: this.roleName})
      this.total = +(res.data.total)
      this.tableData = res.data.records
      // 遍历tableData数组
      this.tableData.forEach(li => {
        li.roleId = +li.roleId
        let rights = [{}]
        // 遍历当前li对象的menuIds数组
        li.menuIds.forEach(id => {
          let right = []
          // 从menus数组中找到对应的menu对象
          const [menu] = this.menus.filter(item => item.menuId === id)
          // 如果找到了menu对象
          if (menu !== undefined) {
            // 将pid转为数字并添加到right数组中
            right.push((menu.parentId))
            // 将menuId转为数字并添加到right数组中
            right.push((menu.menuId))
            // 将right数组添加到rights数组中
            rights.push(right)
          }
        })
        li.rights = rights  // 将rights数组赋值给li对象的rights属性
      })
      this.loading = false
    },
    //清空权限
    delRole(roleId) {
      this.$confirm("此操作将清空该角色所有权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 删除用户事件
        delRights(roleId).then((res) => {
          ElMessage({type: 'success', message: res.msg})
          this.searchJuris()
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        })
      })
    },
    //添加角色
    addRoleBtn() {
      createAuthority(this.addForm).then((res) => {
        if (res.code === 0) {
          ElMessage({type: 'success', message: res.msg})
          this.dialogState = false
          this.searchJuris()
          this.addForm = {}
        }
      })
    },
    //删除角色
    delRoleBtn(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteAuthority(row.roleId).then((res) => {
          if (res.code === 0) {
            ElMessage({type: 'success', message: res.msg})
            this.searchJuris()
          }
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        })
      })
    },
    //修改角色
    updateBtn(row) {
      this.addForm = row
    },
    // 确定修改的按钮事件
    updateTrue() {
      updateAuthority(this.addForm).then((res) => {
        if (res.code === 0) {
          ElMessage({type: 'success', message: res.msg})
          this.dialogState = false
          this.searchJuris()
          this.addForm = {}
        }
      })
    }
  }
}
</script>

<style scoped>
.el-header {
  padding: 20px
}

.el-pagination {
  margin: 20px auto
}

.el-input {
  width: 200px
}
</style>
